/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mbox.server;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import mbox.helper.Utilities;
import mbox.model.Message;


/**
 *
 * @author Hallucinogen
 */
public class Server {
    public Server() throws IOException {
        mServer = new ServerSocket(Utilities.SERVER_PORT);
        mClientSockets = new ArrayList<Socket>();
    }

    public void start()  {
        System.out.println("Server started.... \nListening to port " + Utilities.SERVER_PORT);
        while (true) {
            try {
                Socket clientSocket = mServer.accept();
                
                clientSocket.setSoTimeout(Utilities.SERVER_TIMEOUT);
                System.out.println("Accepting socket from " + clientSocket.getRemoteSocketAddress().toString());

                new ServerHandler(this, clientSocket).start();
                synchronized (this) {
                    mClientSockets.add(clientSocket);
                    ArrayList<Socket> deleted = new ArrayList<Socket>();
                    for (int i = 0; i < mClientSockets.size(); ++i) {
                        Socket socket = mClientSockets.get(i);

                        try {
                            OutputStream os = socket.getOutputStream();
                            // ngecek apakah socket nya masih idup pa ngga
                            os.write(Message.MESSAGE_KEEP_ALIVE);
                            os.flush();
                        } catch (IOException iEx) {
                            System.out.println("Socket not connected");
                            socket.close();
                        }

                        if (socket.isClosed() || !socket.isConnected() || !socket.isBound())
                            deleted.add(mClientSockets.get(i));
                    }

                    for (int i = 0; i < deleted.size(); ++i)
                        mClientSockets.remove(deleted.get(i));
                }
                System.out.println("Handled socket = " + mClientSockets.size());
            } catch (IOException iEx) {
                System.out.println("Error caused by " + iEx);
            }
        }
    }

    public static void main(String[] args) {
        try {
            Server server = new Server();

            server.start();
        } catch (IOException iEx) {
            System.out.println("Server failure! Reason : " + iEx);
        }
    }

    private ServerSocket mServer;
    private ArrayList<Socket> mClientSockets;
}
